<template>
  <div>
    <div id="map"></div>
    <div id="label" v-show="istimecow">
      <div class="block">
        <el-slider
          show-stops
          :step="slider_step"
          v-model="slider_value"
          :marks="marks">
        </el-slider>
        <button @click="autovalue" >启动</button>
        <button @click="jump" >跳转</button>
      </div>
        <!-- <div>
          <div id="circl" style="width:10px;height:10px;border-radius:50%;background-color:red;display: inline-block;"></div>
          <div id="longline" style="position: relative; right:7px; bottom: 2px;  width:200px;height:5px;border-radius:4px;background-color:red;display: inline-block;"></div>
          <div id="circl" style="width:10px;height:10px;border-radius:50%;background-color:red;display: inline-block;"></div>
          <div id="longline" style="position: relative; right:7px; bottom: 2px;  width:200px;height:5px;border-radius:4px;background-color:red;display: inline-block;"></div>
        </div> -->
      <!-- <button  v-for="(item,i) in backroad[0].path " :key="i" @click="clik(i)">225</button> -->
    </div>
    <div class="butongeop" >
      <button  @click="opentimecow" >打开时间轴</button>
    </div>
  </div>
</template>
<script>
// const mapboxgl = require('mapbox-gl')
import {Scene, PointLayer, LineLayer, Popup, MarkerLayer, Marker, Layers} from '@antv/l7'
import { Mapbox } from '@antv/l7-maps'
// import { ProvinceLayer } from '@antv/l7-district'
// import {DrawControl} from '@antv/l7-draw'
export default {
  data () {
    return {
      istimecow: true, // 时间轴是否显示
      timer: '',
      scene: '',
      slider_step: 10,
      slider_value: 0,
      marks: {},
      goonlayer: '',
      enjson: {
        'type': 'MultiPoint',
        'features': [
          {
            'type': 'MultiPoint',
            'properties': {
              'time': ['1997-10-7',
                '2004-5-9',
                '2005-6-3',
                '2077'
              ]
            },
            'geometry': {
              'type': 'MultiPoint',
              'coordinates': [
                [113.13968171093748, 22.99435992515203],
                [114.83157624218748, 27.834761294695152],
                [117.24856842968748, 31.873414026853414],
                [115.75442780468748, 38.40673471648787]
              ]
            }
          }
        ]
      },
      // 轨迹参数
      backroad: [{
        'id': '01',
        'color': [238, 161, 7], // 轨迹线颜色
        'path': [[113.13968171093748, 22.99435992515203], // 轨迹点
          [114.83157624218748, 27.834761294695152],
          [117.24856842968748, 31.873414026853414],
          [115.75442780468748, 38.40673471648787]
        ],
        'time': ['1997-10-7', // 滑动框点
          '2004-5-9',
          '2005-6-3',
          '2077'
        ]
      }],
      ready: [{
        'id': '01',
        'color': [238, 161, 7],
        'path': []
      }],
      // 点标记
      backpoint: {
        features: [
          {'coordinates': [113.13968171093748, 22.99435992515203]},
          {'coordinates': [114.83157624218748, 27.834761294695152]},
          {'coordinates': [117.24856842968748, 31.873414026853414]},
          {'coordinates': [115.75442780468748, 38.40673471648787]}
        ],
        text: [
          'sdgsgsdgs',
          'sdgsd',
          'sdfrsdf',
          'dsfhgdfhd'
        ]
      }
    }
  },
  watch: {
    // value值自加
    slider_value () {
      var that = this
      if (that.istimecow) {
        var len = 100 / (that.backroad[0].time.length - 1)
        var location = that.slider_value / len
        that.roadchange(location)
        // 制作弹窗
        var html = '<strong>Ballston Arts & Crafts Market</strong>'
        var lng = that.backroad[0].path[location][0]
        var lat = that.backroad[0].path[location][1]
        const popup = new Popup().setLnglat([Number(lng), Number(lat)]).setHTML(html)
        that.scene.addPopup(popup)
      }
    }
  },
  mounted () {
    var that = this
    var len = 100 / (that.backroad[0].time.length - 1)
    for (let i = 0, r = 0; i < 101; i = i + len, r++) {
      that.marks[i] = that.backroad[0].time[r]
    }
    this.slider_step = len
    that.marks = JSON.parse(JSON.stringify(that.marks))
    this.initmap()
    this.initLineLayer()
  },
  methods: {
    opentimecow () {
      this.slider_value = 1 // 赋值为1使当出发点为原点时重新赋值为0，触发watch
      this.istimecow = true
    },
    // 防抖
    debounece (fun, waittime) {
      let time = null
      if (time) {
        clearTimeout(time)
      }
      time = setTimeout(fun, waittime)
    },
    jump () {
      this.$router.push({
        path: '/page1'
      })
    },
    autovalue () {
      var that = this
      this.slider_value = 0
      if (this.timer) { clearInterval(that.timer) }
      var len = 100 / (that.backroad[0].time.length - 1)
      this.timer = setInterval(function () {
        if (that.slider_value >= 100) {
          clearInterval(that.timer)
        } else {
          that.slider_value = len + that.slider_value
        }
      }, 1000)
    },
    initmap () {
      const scene = new Scene({
        id: 'map',
        map: new Mapbox({
          center: [109.44827546093748, 34.12140820624562],
          zoom: 2,
          style: 'dark'
        })
      })

      // mapboxgl.accessToken = 'pk.eyJ1IjoiZXppb2dyYWRlIiwiYSI6ImNrZXd0NXM5ZTBvNXcyc25vbjhtNHZoaWEifQ.SbkyAyH_ZCUVEQY_99eTxw'
      // // eslint-disable-next-line no-unused-vars
      // var map = new mapboxgl.Map({
      //   container: 'map', // container id 绑定的组件的id
      //   style: 'mapbox://styles/mapbox/streets-v11',
      //   center: [-74.006, 40.7128],
      //   zoom: 8, // starting zoom 地图初始的拉伸比例
      //   antialias: true // 抗锯齿，通过false关闭提升 性能
      // })

      // const scene = new Scene({
      //   id: 'map',
      //   map: new Mapbox({
      //     mapInstance: map,
      //   }),
      // });

      // const drawControl = new DrawControl(scene, {
      //   position: 'topright',
      //   layout: 'horizontal', // horizontal vertical
      //   controls: {
      //     point: true,
      //     polygon: true,
      //     line: true,
      //     circle: true,
      //     rect: true,
      //     delete: true
      //   }
      // })

      // const zoomControl = new Zoom({
      //   position: 'topleft'
      // })
      // const scaleControl = new Scale({
      //   position: 'bottomleft'
      // })

      // drawControl.on('draw.delete', () => { window.console.log('控件被删除') })
      // drawControl.on('draw.create', (e) => { window.console.log(e) })

      // scene.addControl(drawControl)
      // scene.addControl(scaleControl)
      // scene.addControl(zoomControl)
      this.scene = scene
      // this.map=map;
    },

    getColor (v) {
      var color = ''
      switch (true) {
        case (v > 50): color = '#005a32'; break
        case (v <= 50 && v > 40):color = '#238443'; break
        case (v <= 40 && v > 30):color = '#41ab5d'; break
        case (v <= 30 && v > 20):color = '#78c679'; break
        case (v <= 20 && v > 10):color = '#addd8e'; break
        case (v <= 10 && v > 5): color = '#d9f0a3'; break
        case (v <= 5 && v > 0): color = '#f7fcb9'; break
        case (v <= 0): color = '#ffffe5'; break
      }
      return color
    },

    layerControlOverride (name, laye) {
      var that = this
      var overlayers
      var lastlayer = []
      for (var i = 0, leng = that.scene.controlService.controls.length; i < leng; i++) {
        if (that.scene.controlService.controls[i].constructor.name === 'Layers') {
          lastlayer = that.scene.controlService.controls[i].layers
          that.scene.controlService.controls[i].remove() // 删除旧控件
        }
      }

      if (name && laye) {
        overlayers = {[name]: laye}
      }
      for (var j = 0, len = lastlayer.length; j < len; j++) {
        overlayers[lastlayer[j].name] = lastlayer[j].layer
      }
      const layersControl = new Layers({
        overlayers
      })
      this.scene.addControl(layersControl)
    },

    addMarkers () {
      var that = this
      fetch(
        'https://gw.alipayobjects.com/os/basement_prod/67f47049-8787-45fc-acfe-e19924afe032.json'
      )
        .then(res => res.json())
        .then(nodes => {
          const markerLayer = new MarkerLayer()
          for (let i = 0; i < nodes.length; i++) {
            if (nodes[i].g !== '1' || nodes[i].v === '') {
              continue
            }
            const el = document.createElement('label')
            el.className = 'labelclass'
            el.textContent = nodes[i].v + '℃'
            el.style.background = this.getColor(nodes[i].v)
            el.style.borderColor = this.getColor(nodes[i].v)
            const marker = new Marker({
              element: el
            }).setLnglat({ lng: nodes[i].x * 1, lat: nodes[i].y })
            markerLayer.addMarker(marker)
          }
          that.scene.addMarkerLayer(markerLayer)
        })
    },
    // 标记点，并捆绑点击事件
    point () {
      var html
      var that = this
      this.scene.addImage(
        'marker',
        'https://gw.alipayobjects.com/mdn/antv_site/afts/img/A*BJ6cTpDcuLcAAAAAAAAAAABkARQnAQ'
      )

      const imageLayer = new PointLayer()
      // .source(that.enjson.features[0].geometry)
        .source(this.backpoint.features, {
          parser: {
            type: 'json',
            coordinates: 'coordinates'
          }
        })
        .shape('marker')
        .size(12)
      this.scene.addLayer(imageLayer)

      imageLayer.on('click', function (e) {
        html = '<h1>' + that.backpoint.text[e.featureId] + '</h1>'
        const popup = new Popup().setLnglat([e.lngLat.lng, e.lngLat.lat]).setHTML(html)
        that.scene.addPopup(popup)
      })
    },

    initLineLayer () {
      var that = this
      this.point()
      this.ready[0].path.push(that.backroad[0].path[0])

      const lineLayer = new LineLayer()
        .source(this.ready, {
          parser: {
            type: 'json',
            coordinates: 'path'
          }
        })
        .size(1.5)
        .shape('line')
        .color('color', v => {
          return `rgb(${v})`
        })
        .animate({
          interval: 0.6,
          trailLength: 1.5,
          duration: 6
        })
      this.scene.addLayer(lineLayer)
      this.goonlayer = lineLayer
    },

    // 路径变化
    roadchange (e) {
      var that = this
      this.ready[0].path.length = 0

      for (let i = 0; i <= e; i++) {
        that.ready[0].path.push(this.backroad[0].path[i])
      }
      this.goonlayer.setData(this.ready)
    }

  }

}
</script>

<style >

::-webkit-scrollbar {
  display: none;
}

html,
body {
  overflow: hidden;
  margin: 0;
}

#map {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  /* cursor: pointer !important;
  position :relative; */
}
.el-tooltip__popper{
  visibility: hidden;
}
.butongeop{
  position: absolute;
  background-color: blanchedalmond;
  width: 120px;
  height:10px;
  left: 50px;
  top: 50px;
  padding: 10px;
}
#label {
  position: absolute;
  background-color: blanchedalmond;
  width: 1200px;
  height:200px;
  left: 50px;
  bottom: 50px;
  padding: 10px;
}
.block{
  width:1000px;
  margin: 0 auto;
}
</style>
